<template>
  <div class="accommodation-manage">
    <div class="page-header">
      <h1>住宿管理</h1>
      <el-button type="primary" @click="addAccommodation" :icon="Plus">
        添加住宿
      </el-button>
    </div>

    <div class="search-bar">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索住宿名称..."
        :prefix-icon="Search"
        @input="searchAccommodations"
        style="width: 300px"
      />
    </div>

    <el-table :data="filteredAccommodations" style="width: 100%" stripe>
      <el-table-column prop="id" label="ID" width="60" />
      <el-table-column label="图片" width="100">
        <template #default="{ row }">
          <div class="accommodation-image">
            <img 
              v-if="row.image" 
              :src="IMAGE_BASE_URL + row.image" 
              :alt="row.name"
              class="accommodation-thumbnail"
              @error="handleImageError"
            />
            <el-icon v-else class="no-image-icon" size="40"><Picture /></el-icon>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="住宿名称" width="180" />
      <el-table-column prop="type" label="类型" width="100">
        <template #default="{ row }">
          <el-tag :type="getTypeColor(row.type)">{{ row.type || '未设置' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="location" label="位置" width="150" />
      <el-table-column prop="priceRange" label="价格范围" width="120">
        <template #default="{ row }">
          <span style="color: #e74c3c; font-weight: bold;">
            {{ row.priceRange || '面议' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述" width="200">
        <template #default="{ row }">
          <el-tooltip :content="row.description" placement="top">
            <span>{{ truncateText(row.description, 40) }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160">
        <template #default="{ row }">
          <el-button size="small" @click="editAccommodation(row)" :icon="Edit">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteAccommodation(row.id)" :icon="Delete">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="showDialog"
      :title="isEditing ? '编辑住宿' : '添加住宿'"
      width="80%"
      @close="closeDialog"
    >
      <el-form :model="currentAccommodation" label-width="100px" :rules="formRules">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="住宿名称" prop="name">
              <el-input v-model="currentAccommodation.name" placeholder="请输入住宿名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="住宿类型" prop="type">
              <el-select v-model="currentAccommodation.type" placeholder="请选择类型">
                <el-option label="四星级酒店" value="四星级酒店" />
                <el-option label="特色民宿" value="特色民宿" />
                <el-option label="经济型酒店" value="经济型酒店" />
                <el-option label="豪华酒店" value="豪华酒店" />
                <el-option label="青年旅社" value="青年旅社" />
                <el-option label="度假村" value="度假村" />
                <el-option label="客栈" value="客栈" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="位置" prop="location">
              <el-input v-model="currentAccommodation.location" placeholder="请输入具体位置" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="价格范围">
              <el-input v-model="currentAccommodation.priceRange" placeholder="如：300-600元/晚" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="currentAccommodation.description"
            type="textarea"
            :rows="3"
            placeholder="请输入住宿描述"
          />
        </el-form-item>
        
        <el-form-item label="特色设施">
          <el-input
            v-model="currentAccommodation.facilities"
            type="textarea"
            :rows="2"
            placeholder="如：免费WiFi、停车场、游泳池、健身房等"
          />
        </el-form-item>
        
        <el-form-item label="周边景点">
          <el-input
            v-model="currentAccommodation.nearbyAttractions"
            type="textarea"
            :rows="2"
            placeholder="请描述周边主要景点和距离"
          />
        </el-form-item>
        
        <!-- 图片选择 -->
        <el-form-item label="住宿图片">
          <div class="image-selector-container">
            <ImageSelector 
              v-model="currentAccommodation.image" 
              @change="handleImageChange"
              placeholder="选择住宿图片"
            />
            <div class="image-preview" v-if="currentAccommodation.image">
              <h4>当前图片预览：</h4>
              <img 
                :src="IMAGE_BASE_URL + currentAccommodation.image" 
                :alt="currentAccommodation.name"
                class="preview-image"
                @error="handleImageError"
              />
            </div>
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="saveAccommodation">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Edit, Delete, Picture } from '@element-plus/icons-vue'
import ImageSelector from '@/components/ImageSelector.vue'

const API_BASE_URL = 'http://localhost:8080/api'
const IMAGE_BASE_URL = 'http://localhost:8080/'

interface Accommodation {
  id?: number
  name: string
  description: string
  image: string
  location: string
  type: string
  priceRange: string
  facilities: string
  nearbyAttractions: string
}

const accommodations = ref<Accommodation[]>([])
const filteredAccommodations = ref<Accommodation[]>([])
const searchKeyword = ref('')
const showDialog = ref(false)
const isEditing = ref(false)
const currentAccommodation = ref<Accommodation>({
  name: '',
  description: '',
  image: '',
  location: '',
  type: '',
  priceRange: '',
  facilities: '',
  nearbyAttractions: ''
})

const formRules = {
  name: [
    { required: true, message: '请输入住宿名称', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择住宿类型', trigger: 'change' }
  ],
  location: [
    { required: true, message: '请输入位置', trigger: 'blur' }
  ]
}

const loadAccommodations = async () => {
  try {
    const response = await fetch(`${API_BASE_URL}/accommodations`)
    if (response.ok) {
      accommodations.value = await response.json()
      filteredAccommodations.value = accommodations.value
    } else {
      ElMessage.error('加载住宿数据失败')
    }
  } catch (error) {
    console.error('加载住宿数据失败:', error)
    ElMessage.error('加载住宿数据失败')
  }
}

const searchAccommodations = () => {
  if (!searchKeyword.value.trim()) {
    filteredAccommodations.value = accommodations.value
  } else {
    filteredAccommodations.value = accommodations.value.filter(accommodation =>
      accommodation.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  }
}

const getTypeColor = (type: string) => {
  switch (type) {
    case '四星级酒店':
    case '豪华酒店': return 'warning'
    case '特色民宿': return 'success'
    case '经济型酒店': return 'info'
    case '青年旅社': return 'primary'
    case '度假村': return 'danger'
    default: return ''
  }
}

const truncateText = (text: string, length: number) => {
  if (!text) return ''
  return text.length > length ? text.substring(0, length) + '...' : text
}

const addAccommodation = () => {
  currentAccommodation.value = {
    name: '',
    description: '',
    image: '',
    location: '',
    type: '',
    priceRange: '',
    facilities: '',
    nearbyAttractions: ''
  }
  isEditing.value = false
  showDialog.value = true
}

const editAccommodation = (accommodation: Accommodation) => {
  currentAccommodation.value = { ...accommodation }
  isEditing.value = true
  showDialog.value = true
}

const saveAccommodation = async () => {
  try {
    const url = isEditing.value 
      ? `${API_BASE_URL}/accommodations/${currentAccommodation.value.id}`
      : `${API_BASE_URL}/accommodations`
    
    const method = isEditing.value ? 'PUT' : 'POST'
    
    const response = await fetch(url, {
      method,
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(currentAccommodation.value)
    })
    
    if (response.ok) {
      ElMessage.success(isEditing.value ? '更新成功' : '添加成功')
      closeDialog()
      loadAccommodations()
    } else {
      ElMessage.error(isEditing.value ? '更新失败' : '添加失败')
    }
  } catch (error) {
    console.error('保存住宿失败:', error)
    ElMessage.error('保存住宿失败')
  }
}

const deleteAccommodation = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这个住宿吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    
    const response = await fetch(`${API_BASE_URL}/accommodations/${id}`, {
      method: 'DELETE'
    })
    
    if (response.ok) {
      ElMessage.success('删除成功')
      loadAccommodations()
    } else {
      ElMessage.error('删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除住宿失败:', error)
      ElMessage.error('删除住宿失败')
    }
  }
}

const closeDialog = () => {
  showDialog.value = false
  isEditing.value = false
}

const handleImageError = () => {
  console.warn('图片加载失败')
}

const handleImageChange = () => {
  console.log('图片变化')
}

onMounted(() => {
  loadAccommodations()
})
</script>

<style scoped>
.accommodation-manage {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  color: #2c3e50;
  margin: 0;
}

.search-bar {
  margin-bottom: 20px;
}

.accommodation-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.accommodation-thumbnail {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.no-image-icon {
  color: #909399;
}

.image-selector-container {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.image-preview {
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 8px;
  background: #f9f9f9;
}

.image-preview h4 {
  margin: 0 0 10px 0;
  color: #2c3e50;
  font-size: 14px;
}

.preview-image {
  max-width: 300px;
  max-height: 200px;
  object-fit: cover;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 